# coding=utf-8
#

"""
serializer的入口文件
"""

import uuid
from datetime import date
from datetime import datetime
from django.db.models.query import QuerySet

from iminer.utils import format_datetime


def format_model_response(ret):
    """
    将给定的model response格式化成jsonify的dict，方便API返回

    Args:
        :param ret(QuerySet or Model Instance)

    Returns:
        [{}, {}, ...] or {}
    """

    if isinstance(ret, (QuerySet, list)):
        return [format_model_response(x) for x in ret]
    else:
        r = {}
        if ret:
            for key, val in ret.__dict__.items():
                if key.startswith("_"):
                    continue # 内置属性，pass
                elif isinstance(val, (datetime, date)):
                    r[key] = format_datetime(val)
                elif key == "id":
                    r[key] = str(val)
                else:
                    #val = val or ""
                    r[key] = val

            if isinstance(r["id"], uuid.UUID):
                r["id"] = str(r["id"])

            if "user_id" in r:
                r["user"] = r.pop("user_id")

            if "password" in r:
                r.pop("password")

        return r
